<script setup>
import {ref, onMounted} from "vue";
import axios from "axios";
import {ElMessage, ElNotification} from "element-plus";
import AddRisk from "./child/AddRisk.vue";
import AssignProcessors from "./child/AssignProcessors.vue";
import EventDetail from "./child/EventDetail.vue";
import CancelEvent from "./child/CancelEvent.vue";
import ProcessorsDispose from "./child/ProcessorsDispose.vue";
import DeleteEvent from "./child/DeleteEvent.vue";
import EditRiskDispose from "./child/EditEventDispose.vue";
import ResendTransferProcessors from "./child/ResendTransferProcessors.vue";

onMounted(() => {
  getTableData()
  checkTips()
})
//分页插件相关变量
const totalItems = ref()
const params = ref({
  pageNum: 1,
  pageSize: 10,
  status: null,
  startDate: '',
  endDate: '',
})
const dindDateRange = ref([]);
//定义表格绑定数据
const tableData = ref([])
//获取表格中数据
const getTableData = () => {
  if (dindDateRange.value == null || dindDateRange.value.length == 0) {
    params.value.startDate = null
    params.value.endDate = null
  } else {
    params.value.startDate = dindDateRange.value[0].toISOString();
    params.value.endDate = dindDateRange.value[1].toISOString();
  }

  axios.post('/eventDispose/pageRiskDispose', params.value).then(resp => {
    tableData.value = resp.data.records
    totalItems.value = resp.data.total
  }).catch(err => {
    ElMessage.warning(err.response.data)
  })
}

//翻页触发
const handleCurrentChange = val => {
  params.value.pageNum = val
  getTableData()
}

//每行样式判断选择
const tableRowClassName = ({row, rowIndex}) => {
  if (row.eventDispose.status === 0) {
    return 'transferred'
  } else if (row.eventDispose.status === 1) {
    return 'processing'
  } else if (row.eventDispose.status === 2) {
    return 'completed'
  } else if (row.eventDispose.status === -1) {
    return 'cancelled'
  }
}

//新增组件相关参数
const addEventVisiable = ref(false)
const eventDetailVisiable = ref(false)
const editEventVisiable = ref(false)
const editEventDisposeVisiable = ref(false)
const cancelEventVisiable = ref(false)
const deleteEventVisiable = ref(false)
const assignProcessorsVisiable = ref(false)
const resendProcessorsVisiable = ref(false)
const processorsDisposeVisiable = ref(false)
const currentEventDetail = ref(null)
//点击新增按钮触发
const showAddEvent = () => {
  addEventVisiable.value = true
}
//父传子关闭新增界面
const addEventClose = val => {
  addEventVisiable.value = val;
  getTableData()
}
//点击指派按钮触发
const handleAssignProcessors = val => {
  assignProcessorsVisiable.value = true
  currentEventDetail.value = val;
}
//父传子关闭指派界面
const assignProcessorsClose = val => {
  assignProcessorsVisiable.value = val;
  getTableData()
}

const handleDispose = val => {
  processorsDisposeVisiable.value = true
  currentEventDetail.value = val
}
const processorsDisposeClose = val => {
  processorsDisposeVisiable.value = val
  getTableData()
}

//点击转派按钮触发
const handleReassign = val => {
  resendProcessorsVisiable.value = true
  currentEventDetail.value = val
}
//父传子关闭转派界面
const resendProcessorsClose = val => {
  resendProcessorsVisiable.value = val;
  getTableData()
}
//点击查看按钮触发
const handleView = eventId => {
  axios.get(`/event/getEventDetail/${eventId}`).then(resp => {
    currentEventDetail.value = resp.data;
    eventDetailVisiable.value = true
  }).catch(err => {
    ElMessage.warning(err.response.data)
  })
}
//父传子关闭详情界面
const eventDetailClose = val => {
  eventDetailVisiable.value = val
  getTableData()
}

const handleEdit = val => {
  currentEventDetail.value = val
  editEventDisposeVisiable.value = true
}
const editEventDisposeClose = val => {
  editEventDisposeVisiable.value = val
  getTableData()
}


//点击撤回按钮触发
const handleCancel = val => {
  currentEventDetail.value = val
  cancelEventVisiable.value = true
}
const cancelEventClose = val => {
  cancelEventVisiable.value = val
  getTableData()
}

//点击删除按钮触发
const handleDelete = val => {
  currentEventDetail.value = val
  deleteEventVisiable.value = true
}

const deleteEventClose = val => {
  deleteEventVisiable.value = val
  getTableData()
}

const getPriorityColorByPriority = (priority) => {
  switch (priority) {
    case 1:
      return 'green';
    case 2:
      return 'blue';
    case 3:
      return 'orange';
    case 4:
      return 'red';
    default:
      return 'black';
  }
}

const getPriorityTextByPriority = priority => {
  switch (priority) {
    case 1:
      return '低级';
    case 2:
      return '中级';
    case 3:
      return '高级';
    case 4:
      return '最高级';
    default:
      return '未知';
  }
}

const getStatusTextByStatus = status => {
  switch (status) {
    case 0:
      return '已转办';
    case 1:
      return '处理中';
    case 2:
      return '已完成';
    case -1:
      return '已撤回';
    default:
      return '未知状态';
  }
}

const selectStatus = ref(null)
const handleStatusChange = val => {
  if (val == null) {
    params.value.status = null;
  } else {
    params.value.status = val
  }
}

const checkTips = () => {
  const riskTrea = localStorage.getItem('RiskTrea');
  if(riskTrea!='true'){
    axios.get('/eventDispose/statisticsCurrentUserRisk').then(resp => {
      let count;
      let overdueCount;
      count = resp.data[0];
      if(count==0){
        ElNotification({
          title: '通知',
          message: `暂无需要处理的隐患`,
          type: 'success',
        })
      }else{
        overdueCount=resp.data[1]
        ElNotification({
          title: '通知',
          message: `存在 ${count} 个处理中的隐患，其中 ${overdueCount} 个隐患 预计时间 已到期或3天内到期`,
          type: 'warning',
        })
      }
    }).catch(err => {
      ElMessage.warning(err)
    })

    // 设置本地存储标志，表示通知已经显示过
    localStorage.setItem('RiskTrea', 'true');
  }
}
</script>

<template>
  <div class="hidden-management">

    <el-card class="button-card">
      <el-row class="header-row">
        <el-form-item>
          <el-col class="title">隐患处理</el-col>
        </el-form-item>
      </el-row>

      <el-row class="flex-row" type="flex" justify="space-between" align="middle">
        <!-- 充电桩站查找和时间范围查找 -->
        <el-col class="search-group" :span="10">
          <el-form-item label="处理状态" label-width="80px" style="margin-bottom: 20px">
            <el-select v-model="selectStatus" placeholder="选择状态" style="width: 120px"
                       @change="handleStatusChange" clearable :value-on-clear="null">
              <el-option label="处理中" :value="1"/>
              <el-option label="已完成" :value="2"/>
              <el-option label="已转办" :value="0"/>
              <el-option label="已撤回" :value="-1"/>
            </el-select>
          </el-form-item>
          <el-form-item label="预计完成时间" style="margin-left: 20px; margin-bottom: 20px">
            <el-date-picker
                v-model="dindDateRange"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                range-separator="至"
                style="width: 300px;">
            </el-date-picker>
          </el-form-item>
          <el-form-item label=" " style="margin-bottom: 20px">
            <el-button type="primary" @click="getTableData" style="margin-right: 10px;">查询</el-button>
          </el-form-item>
        </el-col>

        <!-- 查询按钮和新增按钮 -->
        <el-col class="button-group" :span="6">
          <el-form-item>

          </el-form-item>
        </el-col>
      </el-row>
    </el-card>

    <el-card class="table-card">
      <el-row class="table-row">
        <el-col>
          <el-table
              :data="tableData"
              style="width: 100%"
              class="custom-table"
              :row-class-name="tableRowClassName"
          >
            <!--<el-table-column prop="eventDispose.processorsId" label="处理人id" width="100"/>-->
            <el-table-column prop="eventDispose.status" label="处理状态" width="85">
              <template #default="scope">
                <span>{{ getStatusTextByStatus(scope.row.eventDispose.status) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="eventDispose.estimatedTime" label="预计完成时间" width="200"/>

            <!--<el-table-column prop="event.chargingPileId" label="充电桩ID" width="100"/>-->
            <el-table-column prop="event.stationName" label="充电站名称" width="120"/>
            <el-table-column prop="event.pileCode" label="充电桩编号" width="100"/>
            <el-table-column prop="event.address" label="地址位置" width="240"/>

            <el-table-column prop="event.priority" label="优先级" width="80">
              <template #default="scope">
                <span :style="{ color: getPriorityColorByPriority(scope.row.event.priority) }">
                  {{ getPriorityTextByPriority(scope.row.event.priority) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="event.description" label="隐患内容" width="240"/>
            <el-table-column prop="event.created" label="登记时间" width="200"/>
            <el-table-column label="操作" width="240">
              <template v-slot="scope">
                <div class="operation-buttons">
                  <el-button
                      size="small"
                      @click="handleView(scope.row.event.id)"
                  >
                    查看
                  </el-button>

                  <el-button
                      v-if="scope.row.eventDispose.status === 2"
                      size="small"
                      type="primary"
                      @click="handleEdit(scope.row)"
                  >
                    编辑
                  </el-button>

                  <el-button
                      v-if="scope.row.eventDispose.status === 1"
                      size="small"
                      type="warning"
                      @click="handleReassign(scope.row)"
                  >
                    转派
                  </el-button>

                  <el-button
                      v-if="scope.row.eventDispose.status === 1"
                      size="small"
                      type="warning"
                      @click="handleDispose(scope.row)"
                  >
                    处理
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-card>

    <el-row class="pagination-row">
      <el-col :span="24">
        <el-pagination
            background
            layout="prev, pager, next, jumper"
            :current-page="params.pageNum"
            :page-size="params.pageSize"
            :total="totalItems"
            @current-change="handleCurrentChange"
            class="custom-pagination"
        />
      </el-col>
    </el-row>

    <!-- 弹窗组件 -->
    <AddRisk :addEventVisiable="addEventVisiable" @close="addEventClose"/>
    <AssignProcessors
        :assignProcessorsVisiable="assignProcessorsVisiable"
        :currentEventDetail="currentEventDetail"
        @close="assignProcessorsClose"
    />
    <ResendTransferProcessors
        :resendProcessorsVisiable="resendProcessorsVisiable"
        :currentEventDetail="currentEventDetail"
        @close="resendProcessorsClose"
    />
    <EventDetail
        :eventDetailVisiable="eventDetailVisiable"
        :currentEventDetail="currentEventDetail"
        @close="eventDetailClose"
    />
    <EditRiskDispose
        :editEventDisposeVisiable="editEventDisposeVisiable"
        :currentEventDetail="currentEventDetail"
        @close="editEventDisposeClose"
    />
    <CancelEvent
        :cancelEventVisiable="cancelEventVisiable"
        :currentEventDetail="currentEventDetail"
        @close="cancelEventClose"
    />
    <ProcessorsDispose
        :processorsDisposeVisiable="processorsDisposeVisiable"
        :currentEventDetail="currentEventDetail"
        @close="processorsDisposeClose"
    />
    <DeleteEvent
        :deleteEventVisiable="deleteEventVisiable"
        :currentEventDetail="currentEventDetail"
        @close="deleteEventClose"
    />
  </div>
</template>

<style scoped>
.el-table .pending {
  background-color: #ffe4e4; /* 浅红色，代表待处理 */
}

.el-table .processing {
  background-color: #e6f7ff; /* 浅蓝色，代表处理中 */
}

.el-table .transferred {
  background-color: #fff0d5; /* 浅黄色，代表已转办 */
}

.el-table .completed {
  background-color: #d4edda; /* 浅绿色，代表已完成 */
}

.el-table .cancelled {
  background-color: #d3d3d3; /* 浅灰色，代表已撤回 */
}

.title {
  font-size: 24px; /* 增加字体大小 */
  font-weight: bold; /* 加粗字体 */
  text-align: center; /* 如果需要，可以居中显示 */
  padding: 10px 0; /* 增加一些内边距，使标题看起来更有空间感 */
  /* 可以根据需要添加更多样式，如颜色、背景色等 */
  color: #333; /* 例如，设置字体颜色 */
}

.button-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  background-color: #ffffff;
}

.button-group {
  /* 按钮组的样式调整 */
  display: flex;
  flex-direction: column;
  align-items: flex-start; /* 或者使用'center'来水平居中按钮，但在这里我们保持左对齐 */
}
</style>